<template>
	
	<view class="container">
		<view class="header">
			<!-- 搜索栏 end -->
			<view class="center">
				<view class="store">
					<view class="title">
						<image :src="'/static/images/order/order_icon_address.png'" 
								class="left-icon" />
						<!-- 为了测试方便，这里使用静态店铺数据 -->
						<view class="address">{{chooseAddress.houseName}}</view>				
					</view>
					<!-- 外卖&自取switch begin -->
					<view class="buttons1">
						<button type="default"  @tap="switchOrderType">
							切换小区
						</button>
					</view>
				</view>	
				<view class="location">{{chooseAddress.houseAddress}}</view>
				
           </view>
		   
			<!-- 滚动公告栏 begin -->
			<view class="notices">
				<swiper class="swiper" autoplay vertical :interval="3000" :duration="1000" circular>
					<swiper-item v-for="(notice, index) in notices" :key="index">
						<view class="swiper-item">
							<image :src="notice.image" class="image"></image>
							<view class="content">{{ notice.content }}</view>
						</view>
					</swiper-item>
				</swiper>
		<!-- 		<view class="more">
					<text>更多</text>
					<image src="/static/images/common/gray_arrow_down.png" class="down-icon"></image>
				</view> -->
			</view>
		</view>
		<!-- 滚动公告栏 end -->
		<view  v-if="categories.length>0">
		<view class="main">
			<!-- 左侧菜单 begin -->
			<scroll-view class="menu-bar" scroll-y scroll-with-animation>
				<view class="wrapper">
					<view class="menu-item" @tap="handleMenuSelected(category.id)" 
						  :class="{active: currentCategoryId == category.id}" v-for="(category, index) in categories" :key="index">
         <view class="title">{{ category.name }}</view>
					</view>
				</view>  
				
			</scroll-view>
			<!-- 左侧菜单 end -->
			<!-- 右侧商品列表 begin -->
			<scroll-view class="product-section" scroll-y scroll-with-animation :scroll-top="productsScrollTop" @scroll="productsScroll">
				<view class="wrapper">
					
					<view id="ads">
						<!-- 广告栏1 begin -->
						<swiper class="ads1" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" circular>
							<swiper-item v-for="(ad, index) in ads1" :key="index">
								<image :src="ad" class="w-100" mode="widthFix"></image>
							</swiper-item>
						</swiper>
						<!-- 广告栏1 end -->	
					</view>
					
					<!-- 商品 begin -->
					<view class="products-list" v-for="(category, index) in categories" :key="index" :id="`products-${category.id}`">
						<view class="category-name">{{ category.name }}</view>
						<view class="products">
							<view class="product" v-for="(product, key) in category.products" :key="key" 
								@tap="showProductDetailModal(product)">
								<image :src="product.images[0].url" mode="widthFix" class="image"></image>
								<view class="content">
									<view class="name">{{ product.name }}</view>
									<view class="labels">
										<view class="label" 
										:style="{color: label.label_color, background: $commonUtil.hexToRgba(label.label_color, 0.2)}"
										 v-for="label in product.labels" :key="label.id">{{ label.name }}</view>
									</view>
									
				
									<view class="description">{{ product.description }}</view>
									<view class="price">
										<view>￥{{ product.price }}</view>
										<actions :materials-btn="!product.single" 
												@materials="showProductDetailModal(product)" 
												:number="productCartNum(product.id)"
												@add="handleAddToCart(product)" 
												@minus="handleMinusFromCart(product)" />
									</view>
								</view>
							</view>
						</view>
					</view>
					<!-- 商品 end -->
				</view>
			</scroll-view>
			<!-- 右侧商品列表 end -->
		</view>
		<!-- 商品详情 modal begin -->
		<product-modal :product="product" 
						:visible="productModalVisible" 
						@cancel="closeProductDetailModal" 
						@add-to-cart="handleAddToCartInModal" 
		/>
		<!-- 商品详情 modal end -->
		<!-- 购物车栏 begin -->
		<cart-bar :cart="cart" 
				  @add="handleAddToCart" 
				  @minus="handleMinusFromCart"
				  @clear="clearCart"
				  @pay="pay"
		/>
		</view>
		<!-- 当前订单 begin -->
			<view class="no-order-content" v-if="categories.length==0">
				<image src="https://go.cdn.heytea.com/storage/ad/2020/05/20/0bdb360866d94aa4a4404c0b676a1982.jpg"></image>
				<view class="tips">
					<view>您是第一次光顾</view>
					<view>快去选择切换下单吧</view>
				</view>
				<button type="primary" class="font-size-lg" hover-class="none" @tap="switchOrderType">切换地址</button>
			</view>
 </view>
 
</template>

<script>
	import {mapState, mapMutations,mapGetters} from 'vuex'
	import Actions from './components/actions/actions.vue'
	import CartBar from './components/cartbar/cartbar.vue'
	import ProductModal from './components/product-modal/product-modal.vue'
	import cartPopup from './components/cart-popup/cart-popup.vue'
	

	import {
		getCategories
	} from '@/api/water.js';
	
	import {
		thirdPartLogin	
	} from "@/api/user";
	
	export default {
		components: {
			Actions,
			CartBar,
			ProductModal,
			cartPopup
		},
		data() {
			return {
				categories: [],
				cart: [],
				product: {},
				currentCategoryId: 0,
				notices: [],
				ads1: [
					"https://chatx.qiniu.tech-mz.com/image/user/2020/12/09/d6701df3253043d29fef7754b023c478305up4ig96.jpeg",
					"https://chatx.qiniu.tech-mz.com/image/user/2020/12/09/3824eff056ba45e08f1b157a638b781au8hl5k5xcy.jpeg"
				],
				ads2: [
					"https://go.cdn.heytea.com/storage/ad/2020/05/21/acfc6504f3074cf6b730f516adc558f6.jpg",
					"https://go.cdn.heytea.com/storage/ad/2020/04/26/2373600789c64752b2415293877ead40.jpg",
					"https://go.cdn.heytea.com/storage/ad/2020/04/22/515df8c726e740089ae4c55582b4ce09.jpg",
					"https://go.cdn.heytea.com/storage/ad/2020/04/14/d0e51cb22c0a437293c0e6a879b59c7d.jpg"
				],
				productModalVisible: false,
				cartPopupShow: false,
				productsScrollTop: 0,
				showSearch: false,
				chooseAddress: {}
			}
		},
				
		computed: {
			 ...mapGetters(["orderType",'address']),

			 productCartNum() {	//计算单个饮品添加到购物车的数量
				return id => this.cart.reduce((acc, cur) => {
						if(cur.id === id) {
							return acc += cur.number
						}
						return acc
					}, 0)
			}
		},
		async onLoad(options) {	
			// //#ifdef H5
			// //H5进入，有可能是回调进来的
			// if (options.code && options.state) {
			// 	const that = this
			// 	that.logining = true
			// 	thirdPartLogin({loginType: 3,raw: options.code})
			// 		.then(res => {
			// 			that.$store.commit("LOGIN", {'token': res.data.token,});
			// 		 }).catch(data => {
			// 			uni.showToast({title: data,icon:'none',uration:2000});
			// 		})
			//     }
			// //#endif
			
			let val = uni.getStorageSync('chooseAddress');
			if (val != '') {
			   this.getCategories(val);
			}
		},
		methods: {
			...mapMutations(['SET_ORDER_TYPE']),
			
			getNotices: function() {
				let that = this;
				getNotices().then(res => {
					that.notices = res.data;
				});
			},
			
			getCategories: function(addr) {
				let that = this;
				this.chooseAddress=addr;	
				getCategories(addr.houseId).then(res => {
					this.categories = res.data;
					this.currentCategoryId = that.categories.length && that.categories[0].id
					this.$nextTick(() => this.calcSize())			
				});
			},
			
			switchOrderType() {	
				this.clearCart();
				uni.navigateTo({
					url: '/pages/addresses/addresses'
				})
				
			},
			handleAddToCart(product) {	//添加到购物车
				const index = this.cart.findIndex(item => {
					if(!product.single) {
						return (item.id == product.id) && (item.materials_text == product.materials_text)
					} else {
						return item.id === product.id
					}
				})
				
				if(index > -1) {
					this.cart[index].number += (product.number || 1)
					return
				}
				
				this.cart.push({
					id: product.id,
					cate_id: product.category_id,
					name: product.name,
					price: product.price,
					number: product.number || 1,
					image: product.images[0].url,
					single: product.single,
					materials_text: product.materials_text || ''
				})
			},
			handleMinusFromCart(product) { //从购物车减商品
				let index
				if(product.single) {
				   index = this.cart.findIndex(item => item.id == product.id)
				} else {
				   index = this.cart.findIndex(item => (item.id == product.id) && (item.materials_text == product.materials_text))
				}
				this.cart[index].number -= 1
				if(this.cart[index].number <= 0) {
					this.cart.splice(index, 1)
				}
			},
			showProductDetailModal(product) {
				this.product = product
				this.productModalVisible = true
			},
			handleAddToCartInModal(product) {
				this.handleAddToCart(product)
				this.closeProductDetailModal()
			},
			closeProductDetailModal() {
				this.productModalVisible = false
				this.product = {}
			},
			openCartDetailsPopup() {
				this.$refs['cartPopup'].open()
			},
			clearCart() {
				this.cart = []
			},
			handleMenuSelected(id) {
				this.clearCart();
				
				this.productsScrollTop = this.categories.find(item => item.id == id).top
				console.log(this.productsScrollTop)
				
				this.$nextTick(() => this.currentCategoryId = id)
			},
			productsScroll({detail}) {
				const {scrollTop} = detail
				let tabs = this.categories.filter(item=> item.top <= scrollTop).reverse()
				if(tabs.length > 0){
					this.currentCategoryId = tabs[0].id
				}
			},
			calcSize() {
				let h = 0
				let view = uni.createSelectorQuery().select('#ads')
				view.fields({
					size: true
				}, data => {
					h += Math.floor(data.height)
				}).exec()	
				
				this.categories.forEach(item => {
					let view = uni.createSelectorQuery().select(`#products-${item.id}`)
					view.fields({
						size: true
					}, data => {
						item.top = h
						h += Math.floor(data.height)
						item.bottom = h
					}).exec()
				})
			},
			pay() {
				uni.setStorageSync('cart', this.cart)
				uni.navigateTo({
					url: '/pages/pay/pay'
				})
			}
		}
	}
</script>

<style lang="scss">
	@import './index.scss';
	
	.button-class{
		background-color: "#e93323";
	}
	.noCommodity {
		border-top: 7rpx solid #f5f5f5
	}
	
	.noCommodity .pictrue {
		width: 414rpx;
		height: 336rpx;
		margin: 30rpx auto 30rpx auto
	}
	.noCommodity .pictrue image {
		width: 100%;
		height: 100%
	}
	
	.no-order-content {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	
		image {
			width: 300rpx;
			height: 300rpx;
			margin-bottom: 50rpx;
		}
	
		.tips {
			color: $text-color-assist;
			display: flex;
			flex-direction: column;
			align-items: center;
			line-height: 1.2rem !important;
			margin-bottom: 70rpx;
		}
	
		button {
			width: 50%;
		}
	}
</style>
